<template>
  <div class="dashboard-editor-container">
    <panel-group :list="panelGroupData" @handleSetLineChartData="handleSetLineChartData" />
    <el-row style="background:#fff;margin-bottom:16px;">
      <el-col :xs="24" :sm="24" :lg="12">
        <line-chart :chart-data="oeeChartData" />
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <line-chart :chart-data="ctChartData" />
      </el-col>
    </el-row>
    <el-row style="background:#fff;margin-bottom:16px;">
      <bar-chart :chart-data="barChartData" />
    </el-row>
  </div>
</template>

<script>
import { getBasicInfo } from '@/api/basic'
import PanelGroup from '@/components/Charts/PanelGroup.vue'
import LineChart from '@/components/Charts/LineChart.vue'
import BarChart from '@/components/Charts/BarChart.vue'
// import socket from '@/utils/socket'
import screenfull from 'screenfull'
import i18n from '@/lang'
import { parseTime } from '@/utils'

export default {
  name: 'LineView',
  components: {
    PanelGroup,
    LineChart,
    BarChart
  },
  data() {
    return {
      listQuery: {
        page: 1,
        limit: 20,
        state: 3000,
        varName: 'ServerPort',
        lineNumber: '',
        stationNumber: '',
        alarmType: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+processNumber'
      },
      webClose: false,
      panelGroupData: [
        { label: i18n.t('dashboard.stationCount'), num: 0, key: 'lineCount', icon: 'tree' },
        { label: i18n.t('dashboard.processCount'), num: 0, key: 'processCount', icon: 'table' },
        { label: i18n.t('dashboard.produceCount'), num: 0, key: 'produceCount', icon: 'chart' },
        { label: i18n.t('dashboard.failCount'), num: 0, key: 'failCount', icon: 'bug' }],
      barChartData: {
        value1: [],
        value2: [],
        value3: [],
        label: [i18n.t('produce.produceOutput'), i18n.t('produce.okNum'), i18n.t('produce.nokNum')],
        valueX: [],
        title: '机壳上料'
      },
      oeeChartData: {
        valueX: [],
        valueY: [],
        title: 'OEE'
      },
      ctChartData: {
        valueX: [],
        valueY: [],
        title: i18n.t('equipment.cycleTime')
      },
      list: {}
    }
  },
  watch: {
    $route: {
      handler(val) {
        if (this.$route.query.lineNumber !== undefined) {
          this.listQuery.lineNumber = this.$route.query.lineNumber
        }
      }
    }
  },
  mounted() {
    this.listQuery.lineNumber = this.$route.query.lineNumber
    if (this.isEmptyLineId() === false) {
      this.getServerUrl()
    }
    screenfull.toggle()
  },
  created() {
  },
  destroyed() {
    this.close()
  },
  methods: {
    isEmptyLineId: function() {
      var ret = (this.listQuery.lineNumber === undefined || this.listQuery.lineNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    // 获取清单
    getServerUrl() {
      this.listLoading = true
      getBasicInfo(this.listQuery).then(response => {
        this.list = response.data.basicInfos
        this.total = response.data.total
        if (this.total > 0) {
          this.listQuery.varName = this.list[0].varValue
          this.initWebSocket('webSocket')
        } else {
          this.$notify({
            title: this.$i18n.t('common.error'),
            message: i18n.t('msg.GET_SERVER_ADDR_ERR'),
            type: 'error',
            duration: 2000
          })
        }
        this.listLoading = false
      })
    },
    getList(data) {
      this.list = data
      this.panelGroupData[0].num = this.list.counts[0]
      this.panelGroupData[1].num = this.list.counts[1]
      this.panelGroupData[2].num = this.list.counts[2]
      this.panelGroupData[3].num = this.list.counts[3]
      this.barChartData.valueX = this.list.prodChart.ValueX
      this.barChartData.value1 = this.list.prodChart.Value1
      this.barChartData.value2 = this.list.prodChart.Value2
      this.barChartData.value3 = this.list.prodChart.Value3
      this.oeeChartData.valueX = this.list.oeeChart.ValueX
      this.oeeChartData.valueY = this.list.oeeChart.ValueY
      this.ctChartData.valueX = this.list.ctChart.ValueX
      this.ctChartData.valueY = this.list.ctChart.ValueY
      // this.handleSetLineChartData('stationCount')
    },
    handleSetLineChartData(type) {},
    initWebSocket(e) {
      if (typeof WebSocket === 'undefined') {
        console.log(i18n.t('msg.WEBSOCKET_NOT_SUPPORT'))
        return
      }
      const protocol = 'ws'
      // var wsUri = protocol + '://' + '192.168.1.200' + ':' + this.listQuery.varName + process.env.VUE_APP_BASE_API + '/background/' + e
      var wsUri = protocol + '://' + window.location.hostname + ':' + this.listQuery.varName + process.env.VUE_APP_BASE_API + '/background/' + e
      this.socket = new WebSocket(wsUri)
      this.socket.onerror = this.webSocketOnError
      this.socket.onmessage = this.webSocketOnMessage
      this.socket.onclose = this.webSocketOnClose
      this.socket.onopen = this.webSocketOnOpen
    },
    webSocketOnError(e) {
      this.$notify({
        title: '',
        message: 'WebSocket连接发生错误' + e,
        type: 'error',
        duration: 3000
      })
      if (this.webClose === false) {
        setTimeout(() => {
          console.log('开始重连...')
          this.initWebSocket('webSocket')
        }, 10000)
      }
    },
    webSocketOnMessage(e) {
      this.webSocketSend(this.listQuery)
      const data = JSON.parse(e.data)
      console.log(data)
      this.getList(data)
      if (data.msgType === 'INFO') {
        this.$notify({
          title: '',
          message: data.msg,
          type: 'success',
          duration: 3000
        })
      } else if (data.msgType === 'ERROR') {
        this.$notify({
          title: '',
          message: data.msg,
          type: 'error',
          duration: 1000
        })
      }
      return data
    },
    webSocketOnClose() {
      console.log('连接已关闭...')
      if (this.webClose === false) {
        setTimeout(() => {
          console.log('开始重连...')
          this.initWebSocket('webSocket')
        }, 10000)
      }
    },
    webSocketOnOpen() {
      console.log('开启')
      this.webSocketSend(this.listQuery)
    },
    close() {
      this.webClose = true
      this.socket.close() // 关闭
    },
    webSocketSend(agentData) {
      var msg = JSON.stringify(agentData)
      if (this.socket !== undefined && this.socket.readyState === 1) {
        this.socket.send(msg)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding:10px 32px ;
  background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px ;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
